import axios from "axios";
import {useUserStore} from "../stores/userStore";
import {useRouter} from 'vue-router';

let http = axios.create({
  baseURL: "http://localhost:3001",
  // baseURL: "http://175.24.166.50:3003/api",
  timeout: 10000,
  headers: { "Content-Type": "application/json" }
})
// 添加请求拦截器
http.interceptors.request.use(
  function (config) {
    let userStore = useUserStore();
    let token = userStore.token;
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
http.interceptors.response.use(
  function (response) {
    if(response.data.code == "10119"){
      // token无效清除本地数据重新登陆
      let userStore = useUserStore();
      userStore.loginname = "";
      userStore.token = "";
      let router = useRouter();
      router.push("/login");
    }
    return response;
  },
  function (error) {
      return Promise.reject(error);
  }
);
export default http